package com.lf.weixinOriginPay;

import com.alibaba.fastjson.JSONObject;
import com.lf.constant.ConstantsValue;
import com.lf.entity.ResponseWrapper;
import com.lf.enums.ErrorCodeEnum;
import com.lf.exception.ApiException;
import com.lf.jwt.SameUrlData;
import com.lf.service.ServiceList;
import com.lf.swagger.ApiJsonObject;
import com.lf.swagger.ApiJsonProperty;
import com.lf.util.Asserts;
import com.lf.weixinOriginPay.sdk.WXPayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Created by gxl on 2018/5/3.
 */

@Slf4j
@Api(value = "wxPay", tags = "微信支付")
@RestController
@RequestMapping("/wxPay")
public class PayController extends ServiceList {

    /**
     * 统一下单API
     * @param jsonParam
     * @return
     */
    @RequestMapping(value = "/unifiedOrder", method = RequestMethod.POST)
    @ApiOperation(tags = "小程序接口", httpMethod = "POST", value = "[前端]核查比对", response = String.class)
    public ResponseWrapper unifiedOrder(
            @ApiJsonObject(name = "unifiedOrderParams", value = {
                    @ApiJsonProperty(key = "type", value = "消费类型,1:核查月费，3:核查续费，2:代理商费用"),
                    @ApiJsonProperty(key = "userId", value = "用户ID")
            }) @RequestBody JSONObject jsonParam){

        Integer userid = jsonParam.getInteger("userId");
        String type = jsonParam.getString("type");
        Asserts.checkUserId(userid,"用户ID");
        Asserts.notBlank(type,"消费类型");

        try {
            return userService.unifiedOrder(userid,type);
        } catch (ApiException e){
            log.error(String.format("[前端]统一下单接口请求失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(ErrorCodeEnum.WP8010);
        }   catch (Exception e) {
            log.error(String.format("[前端]统一下单接口请求失败，参数:%s, 错误信息:%s", jsonParam.toJSONString(), e.getMessage()));
            return ResponseWrapper.failed(ErrorCodeEnum.WP8010);
        }
    }

    /**
     * 微信支付回调
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/callback", method = RequestMethod.POST)
    @ApiOperation(tags = "微信支付回调", httpMethod = "POST", value = "[微信服务器]微信支付回调", response = String.class)
    public String callback(HttpServletRequest request, HttpServletResponse response){
        redisLockRegistry.obtain(ConstantsValue.COLONY_DRAWN_LOCK).lock();
        ConstantsValue.DRAWN_LOCK.writeLock().lock();
        // 获取微信POST过来反馈信息
        String notityXml = "";
        try {
            String inputLine;
            while ((inputLine = request.getReader().readLine()) != null) {
                notityXml += inputLine;
            }
            request.getReader().close();
            Map<String,String> m = WXPayUtil.xmlToMap(notityXml);
            return userService.wxpayCallback(m);
        } catch (ApiException e) {
            log.error(String.format("[前端]升级代理商失败，参数:%s, 错误信息:%s", notityXml, e.getMessage()));
            return null;
        } catch (Exception e) {
            log.error(String.format("[前端]升级代理商失败，参数:%s, 错误信息:%s", notityXml, e.getMessage()));
            return null;
        }finally {
            ConstantsValue.DRAWN_LOCK.writeLock().unlock();
            redisLockRegistry.obtain(ConstantsValue.COLONY_DRAWN_LOCK).unlock();
        }
    }



    /**
     * 微信支付获取相关签名信息
     * @param session
     * @param url
     * @return
     */
//    @RequestMapping(value = "/getweixinjs" ,method = RequestMethod.POST)
//    @ResponseBody
//    public JSONObject getweixinjs(HttpSession session, String url){
//
//        WeChatTask.ACCESS_TOKEN =  com.alibaba.fastjson.JSONObject.parseObject(HttpUtils.sendGet("http://www.wwhtjy.com/wei/xin/public/get/access/token",new HashMap<String,String>())).getJSONObject("data").getString("access_token");
//        WeChatTask.JSAPI_TICKET =  com.alibaba.fastjson.JSONObject.parseObject(HttpUtils.sendGet("http://www.wwhtjy.com/wei/xin/public/get/jsapi/ticket",new HashMap<String,String>())).getJSONObject("data").getString("ticket");
//        HashMap<String,String> hm = new HashMap<String,String>();
//        try {
//            hm = JSSDK_Config.jsSDK_Sign(url);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return JSONUtils.getRoot(0,"success", JSONObject.toJSON(hm));
//    }

    /**
     * 微信原生支付
     * @param request
     * @return
     */
//    @RequestMapping(value = "/WXPay",method = RequestMethod.GET)
//    @ResponseBody
//    public JSONObject WXPay(HttpServletRequest request){
//        logger.info("进入WXPay函数了，这个函数是属于原生支付");
//        int realmoney = 500;
//
//        MyConfig config = null;
//        try {
//            config = new MyConfig();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        WXPay wxpay = null;
//        try {
//            wxpay = new WXPay(config);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        Map<String, String> data = new HashMap<String, String>();
//        data.put("body", "充值");
//        data.put("out_trade_no", WXPayUtil.generateUUID());
//        data.put("device_info", "WEB");
//        data.put("openid","oKQON0VAjOXXH5A3Lz1Pyl_gAmsE");
//        data.put("fee_type", "CNY");
//        data.put("total_fee", String.valueOf(realmoney));
////        data.put("spbill_create_ip", CusAccessObjectUtil.getIpAddress(request));
//        data.put("spbill_create_ip", "192.168.0.1");
//
//        try {
//            data.put("notify_url", StaticValue.WX.BASE_URL + "/weixinOriginPay/payNoticy");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        data.put("trade_type", "JSAPI");  // 此处指定为扫码支付
//        data.put("product_id", "fb"+WXPayUtil.generateUUID());
//
//        try {
//            Map<String, String> resp = wxpay.unifiedOrder(data);
//            Map<String, String> data2 = new HashMap<String, String>();
//            String paySign = WXPayUtil.generateSignature(data2,config.getKey());
//            data2.put("appId", StaticValue.WX.AppId);
//            data2.put("timeStamp", String.valueOf(System.currentTimeMillis()));
//            data2.put("nonceStr", WXPayUtil.generateUUID());
//            data2.put("package","prepay_id="+resp.get("prepay_id"));
//            data2.put("signType", "MD5");
//            data2.put("paySign",paySign);
//
//            return JSONUtils.getRoot(0,"success",data2);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return JSONUtils.getRoot(1,"faild","");
//        }
//    }
}
